<?php
declare (strict_types = 1);

namespace app\admin\service\data\website;

use app\admin\model\data\PaymentOrderItem;
use app\admin\model\data\Student;
use app\admin\model\data\VisitTotal;
use app\admin\service\data\DataService;

/**
 * 网站访问
 */
class Visit extends DataService
{
    /**
     * 访问量分析
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-27
     * @return   [type]                         [description]
     */
    public function visit()
    {
        $dateList = $this->parseDate();
        $rows     = [];
        foreach ($dateList as $date => $where) {
            $pv     = VisitTotal::getPvByTimespan($where);
            $uv     = VisitTotal::getUvByTimespan($where);
            $rows[] = [
                'date' => $date,
                'pv'   => $pv,
                'uv'   => $uv,
            ];
        }

        return $this->parseToData(['rows' => $rows], 1);
    }

    /**
     * 课程/机构首页访问分析
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-27
     * @return   [type]                         [description]
     */
    public function survey()
    {
        $daterange = $this->parseSelectDaterange();
        $timespan  = $daterange['timespan'];
        $data      = [];
        // 机构PV
        $data['home_pv'] = VisitTotal::whereBetween('visit_time', $timespan)->sum('pv');
        // 机构UV
        $data['home_uv'] = VisitTotal::whereBetween('visit_time', $timespan)->count('DISTINCT ip');
        // 课程PV
        $data['course_pv'] = VisitTotal::whereIn('resource_type', VisitTotal::getCourseResourceTypes())->whereBetween('visit_time', $timespan)->sum('pv');
        // 课程UV
        $data['course_uv'] = VisitTotal::whereIn('resource_type', VisitTotal::getCourseResourceTypes())->whereBetween('visit_time', $timespan)->count('DISTINCT ip');
        $rows              = $this->parseRowsDate($daterange['rows']);
        // 统计图表
        if ($daterange['days'] == 1) {
            // 按小时,此处一天内的小时数不会重复,因此可以直接按小时取
            // 总访问量
            $result = VisitTotal::whereBetween('visit_time', $timespan)->field(['SUM(pv)' => 'tp_pv', 'FROM_UNIXTIME(`visit_time`,"%H:00")' => 'date'])->group('date')->select()->toArray();
            $rows   = $this->parseRows($result, $rows, 'pv');
            // 课程访问量
            $result = VisitTotal::whereIn('resource_type', VisitTotal::getCourseResourceTypes())->whereBetween('visit_time', $timespan)->field(['SUM(pv)' => 'tp_course_pv', 'FROM_UNIXTIME(`visit_time`,"%H:00")' => 'date'])->group('date')->select()->toArray();
            $rows   = $this->parseRows($result, $rows, 'course_pv');
        } else {
            // 按天 pv uv 总访问量
            $result = VisitTotal::whereBetween('visit_time', $timespan)->field(['SUM(pv)' => 'tp_pv', 'FROM_UNIXTIME(`visit_time`,"%Y-%m-%d")' => 'date'])->group('date')->select()->toArray();
            $rows   = $this->parseRows($result, $rows, 'pv');
            // 课程访问量
            $result = VisitTotal::whereIn('resource_type', VisitTotal::getCourseResourceTypes())->whereBetween('visit_time', $timespan)->field(['SUM(pv)' => 'tp_course_pv', 'FROM_UNIXTIME(`visit_time`,"%Y-%m-%d")' => 'date'])->group('date')->select()->toArray();
            $rows   = $this->parseRows($result, $rows, 'course_pv');
        }

        $data['rows'] = $rows;
        // 用户注册来源
        $data['register'] = Student::whereBetween('create_time', $timespan)->group('register_device')->field(['register_device', 'COUNT(1)' => 'tp_count'])->select()->append(['register_device_text'])->toArray();
        // 用户下单来源
        $data['place_order'] = PaymentOrderItem::scope('mhm')->whereBetween('create_time', $timespan)->group('from')->field(['from', 'COUNT(DISTINCT user_id)' => 'tp_count'])->select()->append(['from_text'])->toArray();

        $data['is_platform'] = request()->is_platform;

        return $this->parseToData($data, 1);
    }

    /**
     * 解析统计图指标数据
     * Author   Martinsun<syh@sunyonghong.com>
     * Date 2020-07-21
     * @param    [type]                         $datas [description]
     * @param    [type]                         $rows  [description]
     * @param    [type]                         $field [description]
     * @return   [type]                                [description]
     */
    protected function parseRows($datas, $rows = [], $field)
    {
        $result = array_column($datas, 'tp_' . $field, 'date');

        foreach ($rows as $key => $row) {
            $time               = $row['date'];
            $rows[$key][$field] = isset($result[$time]) ? $result[$time] : 0;
        }

        return $rows;
    }
}
